using System;
using System.Threading.Tasks;
using Codeflows.Results;

namespace Codeflows
{
    class AsyncCompletion
    {
        readonly IDisposable _codeflowContext;

        public AsyncCompletion(IDisposable codeflowContext)
        {
            if (codeflowContext == null) throw new ArgumentNullException("codeflowContext");
            _codeflowContext = codeflowContext;
        }

        public void Complete(Task<Result> task)
        {
            var s = task.Result as SuspendedResult;
            if(s != null)
            {
                DiagnosticsUtility.Error("Unhandled exception executing codeflow.", s.Exception);
                _codeflowContext.Dispose();
                return; 
            }

            var p = task.Result as PendingResult;
            if (p != null)
                p.PendingTask.ContinueWith(Complete);
            else
                _codeflowContext.Dispose();
        }
    }
}